import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    const doctorId = localStorage.getItem('doctorId')
    
    if (token) {
      config.headers['Authorization'] = token
    }
    
    // 如果是医生相关请求，添加doctorId头
    if (doctorId && (config.url.includes('/api/doctor') || config.url.includes('/api/medical-record'))) {
      config.headers['doctorId'] = doctorId
    }
    
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.log('err' + error)
    
    if (error.response) {
      if (error.response.status === 401) {
        ElMessage.error('登录已过期，请重新登录')
        localStorage.clear()
        window.location.href = '/login'
      } else if (error.response.status === 403) {
        ElMessage.error('没有权限访问该资源')
      }
    }
    
    return Promise.reject(error)
  }
)

export default service